package cn.com.cifi.mars.service.impl;

import cn.com.cifi.mars.bean.bo.PanoPlanCastDecisionBO;
import cn.com.cifi.mars.common.exception.MsgException;
import cn.com.cifi.mars.constant.CodeEnum;
import cn.com.cifi.mars.constant.IsDeleteEnum;
import cn.com.cifi.mars.constant.VersionStatusEnum;
import cn.com.cifi.mars.constant.VersionTypeEunm;
import cn.com.cifi.mars.entity.PanoplanBuildPlan;
import cn.com.cifi.mars.entity.PanoplanBuildPlanItem;
import cn.com.cifi.mars.entity.PanoplanBuildPlanItemDetail;
import cn.com.cifi.mars.mapper.mars.PanoplanBuildPlanItemDetailMapper;
import cn.com.cifi.mars.mapper.mars.PanoplanBuildPlanItemMapper;
import cn.com.cifi.mars.mapper.mars.PanoplanBuildPlanMapper;
import cn.com.cifi.mars.service.PanoplanBuildPlanService;
import cn.com.cifi.mars.util.UUIDUtils;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;


/**
 * <p>
 * 楼栋计划表 服务实现类
 * </p>
 *
 * @author yyd
 * @since 2019-09-07
 */
@Service
public class PanoplanBuildPlanServiceImpl extends ServiceImpl<PanoplanBuildPlanMapper, PanoplanBuildPlan> implements PanoplanBuildPlanService {

	private static final Logger log = LoggerFactory.getLogger(PanoplanBuildPlanServiceImpl.class);
	
    @Autowired
    private PanoplanBuildPlanMapper panoplanBuildPlanMapper;

    @Autowired
    private PanoplanBuildPlanItemMapper panoplanBuildPlanItemMapper;

    @Autowired
    private PanoplanBuildPlanItemDetailMapper panoplanBuildPlanItemDetailMapper;

    @Override
    public PanoPlanCastDecisionBO selectNewestByFid(String projectFid, List<String> versionTypes, int isDel) {
        PanoPlanCastDecisionBO panoPlanCastDecisionBO = new PanoPlanCastDecisionBO();
        PanoplanBuildPlan panoplanBuildPlan = panoplanBuildPlanMapper.selectNewestByFid(projectFid, versionTypes, isDel);

        if(panoplanBuildPlan != null){
            queryCastDecisionInfo(isDel, panoPlanCastDecisionBO, panoplanBuildPlan);

            return panoPlanCastDecisionBO;
        }else{
            throw new MsgException(CodeEnum.NON_PANOPLAN_VERSION);
        }
    }

    private void queryCastDecisionInfo(int isDel, PanoPlanCastDecisionBO panoPlanCastDecisionBO, PanoplanBuildPlan panoplanBuildPlan) {
        //分期
        panoPlanCastDecisionBO.setPanoplanBuildPlan(panoplanBuildPlan);

        //组团
        QueryWrapper<PanoplanBuildPlanItem> groupWrapper = new QueryWrapper<PanoplanBuildPlanItem>();
        groupWrapper.eq("pk_id", panoplanBuildPlan.getId()).last(" GROUP BY batch_id");
        List<PanoplanBuildPlanItem> groupItems = panoplanBuildPlanItemMapper.selectList(groupWrapper);
        if(CollectionUtils.isNotEmpty(groupItems)){
            panoPlanCastDecisionBO.setGroupItems(groupItems);
        }else{
            CodeEnum.NON_PANOPLAN_GROUP.setMessage(panoplanBuildPlan.getVersionCode()+ CodeEnum.NON_PANOPLAN_GROUP.getMessage());
            throw new MsgException(CodeEnum.NON_PANOPLAN_GROUP);
        }

        //批次
        QueryWrapper<PanoplanBuildPlanItem> batchWrapper = new QueryWrapper<PanoplanBuildPlanItem>();
        batchWrapper.eq("pk_id", panoplanBuildPlan.getId()).last(" GROUP BY batch_id, batch_num");
        List<PanoplanBuildPlanItem> batchItems = panoplanBuildPlanItemMapper.selectList(batchWrapper);
        if(CollectionUtils.isNotEmpty(batchItems)){
            panoPlanCastDecisionBO.setBatchItems(batchItems);
        }else{
            CodeEnum.NON_PANOPLAN_BATCH.setMessage(panoplanBuildPlan.getVersionCode()+ CodeEnum.NON_PANOPLAN_BATCH.getMessage());
            throw new MsgException(CodeEnum.NON_PANOPLAN_BATCH);
        }

        //产品构成
        QueryWrapper<PanoplanBuildPlanItem> productWrapper = new QueryWrapper<PanoplanBuildPlanItem>();
        productWrapper.eq("pk_id", panoplanBuildPlan.getId()).last(" GROUP BY batch_id, batch_num, product_type_num, decorate_name, sale_type, pro_type");
        List<PanoplanBuildPlanItem> productItems = panoplanBuildPlanItemMapper.selectList(productWrapper);
        if(CollectionUtils.isNotEmpty(productItems)){
            panoPlanCastDecisionBO.setProductItems(productItems);
        }else{
            CodeEnum.NON_PANOPLAN_PRODUT.setMessage(panoplanBuildPlan.getVersionCode()+ CodeEnum.NON_PANOPLAN_PRODUT.getMessage());
            throw new MsgException(CodeEnum.NON_PANOPLAN_PRODUT);
        }

        //供货时间节点
        List<String> itemIds = Optional.of(productItems).orElseGet(ArrayList::new)
                .stream().map(PanoplanBuildPlanItem::getId)
                .collect(Collectors.toList());
        QueryWrapper<PanoplanBuildPlanItemDetail> detailWrapper = new QueryWrapper<PanoplanBuildPlanItemDetail>();
        detailWrapper.in("pk_id", itemIds);
                //.eq("is_send_back", isDel);
        List<PanoplanBuildPlanItemDetail> panoplanBuildPlanItemDetails = panoplanBuildPlanItemDetailMapper.selectList(detailWrapper);
        if (CollectionUtils.isNotEmpty(panoplanBuildPlanItemDetails)){
            panoPlanCastDecisionBO.setDetails(panoplanBuildPlanItemDetails);
        }

    }

    @Override
    public PanoPlanCastDecisionBO selectNewestWarPlanByFid(String projectFid, String versionType, int isDel) {

        List<String> versionTypes = new ArrayList<String>();
        versionTypes.add(VersionTypeEunm.WARPLAN.getValue());
        if(versionType.equals(VersionTypeEunm.GETPRICE.getKey())){
            versionTypes.add(VersionTypeEunm.DYNAMIC.getValue());
        }else if(versionType.equals(VersionTypeEunm.DYNAMIC.getKey())){
            versionTypes.add(VersionTypeEunm.DYNAMIC.getValue());
        }

        PanoPlanCastDecisionBO panoPlanCastDecisionBO = new PanoPlanCastDecisionBO();
        //查询t_panoplan_build_plan->楼栋计划表, 当前分期有没有楼栋计划推送过来 ,
        //如果是创建的动态版,那么查询的楼栋计划的version_type(版本类型)就是 ('战规版', '动态版')最新数据
        //如果楼栋计划表为空,那么代表 楼栋计划还没有推送过来数据,不允许创建版本
        PanoplanBuildPlan panoplanBuildPlan = panoplanBuildPlanMapper.selectNewestByFid(projectFid, versionTypes, isDel);

        if(panoplanBuildPlan != null){
            //分期
            panoPlanCastDecisionBO.setPanoplanBuildPlan(panoplanBuildPlan);

            //组团
            QueryWrapper<PanoplanBuildPlanItem> groupWrapper = new QueryWrapper<PanoplanBuildPlanItem>();
            groupWrapper.eq("pk_id", panoplanBuildPlan.getId()).last(" GROUP BY batch_id");
            List<PanoplanBuildPlanItem> groupItems = panoplanBuildPlanItemMapper.selectList(groupWrapper);
            if(CollectionUtils.isNotEmpty(groupItems)){
                panoPlanCastDecisionBO.setGroupItems(groupItems);
            }else{
            	//楼栋子表-组团楼栋表数据为空,请在楼栋计划系统 推送一条数据
                CodeEnum.NON_PANOPLAN_GROUP.setMessage(CodeEnum.NON_PANOPLAN_GROUP.getMessage());
                CodeEnum.NON_PANOPLAN_GROUP.setMessage("楼栋计划 "+CodeEnum.NON_PANOPLAN_GROUP.getMessage());
                throw new MsgException(CodeEnum.NON_PANOPLAN_GROUP);
            }

            //产品构成
            QueryWrapper<PanoplanBuildPlanItem> productWrapper = new QueryWrapper<PanoplanBuildPlanItem>();
            productWrapper.eq("pk_id", panoplanBuildPlan.getId()).last(" GROUP BY batch_id, product_type_num");
            List<PanoplanBuildPlanItem> productItems = panoplanBuildPlanItemMapper.selectList(productWrapper);
            if(CollectionUtils.isNotEmpty(productItems)){
                panoPlanCastDecisionBO.setProductItems(productItems);
            }else{
            	//楼栋子表-组团楼栋表数据为空,请在楼栋计划系统 推送一条数据
                CodeEnum.NON_PANOPLAN_PRODUT.setMessage(CodeEnum.NON_PANOPLAN_PRODUT.getMessage());
                CodeEnum.NON_PANOPLAN_PRODUT.setMessage("楼栋计划 "+CodeEnum.NON_PANOPLAN_PRODUT.getMessage());
                throw new MsgException(CodeEnum.NON_PANOPLAN_PRODUT);
            }

            //楼栋
            QueryWrapper<PanoplanBuildPlanItem> buildWrapper = new QueryWrapper<PanoplanBuildPlanItem>();
            buildWrapper.eq("pk_id", panoplanBuildPlan.getId()).last(" GROUP BY batch_id, product_type_num, bld_prd_Id");
            List<PanoplanBuildPlanItem> buildItems = panoplanBuildPlanItemMapper.selectList(buildWrapper);
            if(CollectionUtils.isNotEmpty(buildItems)){
                panoPlanCastDecisionBO.setBuildItems(buildItems);
            }else{
            	//楼栋子表-组团楼栋表数据为空,请在楼栋计划系统 推送一条数据
                CodeEnum.NON_PANOPLAN_BUILD.setMessage(CodeEnum.NON_PANOPLAN_BUILD.getMessage());
                CodeEnum.NON_PANOPLAN_BUILD.setMessage("楼栋计划 "+CodeEnum.NON_PANOPLAN_BUILD.getMessage());
                throw new MsgException(CodeEnum.NON_PANOPLAN_BUILD);
            }

            //供货时间节点
            List<String> itemIds = Optional.of(buildItems).orElseGet(ArrayList::new)
                    .stream().map(PanoplanBuildPlanItem::getId)
                    .collect(Collectors.toList());
            QueryWrapper<PanoplanBuildPlanItemDetail> detailWrapper = new QueryWrapper<PanoplanBuildPlanItemDetail>();
            detailWrapper.in("pk_id", itemIds);
                    //.eq("is_send_back", isDel);
            List<PanoplanBuildPlanItemDetail> panoplanBuildPlanItemDetails = panoplanBuildPlanItemDetailMapper.selectList(detailWrapper);
            if (CollectionUtils.isNotEmpty(panoplanBuildPlanItemDetails)){
                panoPlanCastDecisionBO.setDetails(panoplanBuildPlanItemDetails);
            }

            return panoPlanCastDecisionBO;
        }else{
            throw new MsgException(CodeEnum.NON_PANOPLAN_VERSION);
        }
    }

    @Override
    public PanoPlanCastDecisionBO selectNewestWarPlanByFidAndVersionType(String projectFid, String versionType, int isDel) {

        PanoPlanCastDecisionBO panoPlanCastDecisionBO = new PanoPlanCastDecisionBO();
        //查询t_panoplan_build_plan->楼栋计划表, 当前分期有没有楼栋计划推送过来 ,
        //如果是创建的动态版,那么查询的楼栋计划的version_type(版本类型)就是 ('战规版', '动态版')最新数据
        //如果楼栋计划表为空,那么代表 楼栋计划还没有推送过来数据,不允许创建版本
        PanoplanBuildPlan panoplanBuildPlan = panoplanBuildPlanMapper.selectNewestByFid(projectFid, Arrays.asList(versionType), isDel);

        if(panoplanBuildPlan != null){
            //分期
            panoPlanCastDecisionBO.setPanoplanBuildPlan(panoplanBuildPlan);

            //组团
            QueryWrapper<PanoplanBuildPlanItem> groupWrapper = new QueryWrapper<PanoplanBuildPlanItem>();
            groupWrapper.eq("pk_id", panoplanBuildPlan.getId()).last(" GROUP BY batch_id");
            List<PanoplanBuildPlanItem> groupItems = panoplanBuildPlanItemMapper.selectList(groupWrapper);
            if(CollectionUtils.isNotEmpty(groupItems)){
                panoPlanCastDecisionBO.setGroupItems(groupItems);
            }else{
                //楼栋子表-组团楼栋表数据为空,请在楼栋计划系统 推送一条数据
                CodeEnum.NON_PANOPLAN_GROUP.setMessage(CodeEnum.NON_PANOPLAN_GROUP.getMessage());
                CodeEnum.NON_PANOPLAN_GROUP.setMessage("楼栋计划 "+CodeEnum.NON_PANOPLAN_GROUP.getMessage());
                throw new MsgException(CodeEnum.NON_PANOPLAN_GROUP);
            }

            //产品构成
            QueryWrapper<PanoplanBuildPlanItem> productWrapper = new QueryWrapper<PanoplanBuildPlanItem>();
            productWrapper.eq("pk_id", panoplanBuildPlan.getId()).last(" GROUP BY batch_id, product_type_num");
            List<PanoplanBuildPlanItem> productItems = panoplanBuildPlanItemMapper.selectList(productWrapper);
            if(CollectionUtils.isNotEmpty(productItems)){
                panoPlanCastDecisionBO.setProductItems(productItems);
            }else{
                //楼栋子表-组团楼栋表数据为空,请在楼栋计划系统 推送一条数据
                CodeEnum.NON_PANOPLAN_PRODUT.setMessage(CodeEnum.NON_PANOPLAN_PRODUT.getMessage());
                CodeEnum.NON_PANOPLAN_PRODUT.setMessage("楼栋计划 "+CodeEnum.NON_PANOPLAN_PRODUT.getMessage());
                throw new MsgException(CodeEnum.NON_PANOPLAN_PRODUT);
            }

            //楼栋
            QueryWrapper<PanoplanBuildPlanItem> buildWrapper = new QueryWrapper<PanoplanBuildPlanItem>();
            buildWrapper.eq("pk_id", panoplanBuildPlan.getId()).last(" GROUP BY batch_id, product_type_num, bld_prd_Id");
            List<PanoplanBuildPlanItem> buildItems = panoplanBuildPlanItemMapper.selectList(buildWrapper);
            if(CollectionUtils.isNotEmpty(buildItems)){
                panoPlanCastDecisionBO.setBuildItems(buildItems);
            }else{
                //楼栋子表-组团楼栋表数据为空,请在楼栋计划系统 推送一条数据
                CodeEnum.NON_PANOPLAN_BUILD.setMessage(CodeEnum.NON_PANOPLAN_BUILD.getMessage());
                CodeEnum.NON_PANOPLAN_BUILD.setMessage("楼栋计划 "+CodeEnum.NON_PANOPLAN_BUILD.getMessage());
                throw new MsgException(CodeEnum.NON_PANOPLAN_BUILD);
            }

            //供货时间节点
            List<String> itemIds = Optional.of(buildItems).orElseGet(ArrayList::new)
                    .stream().map(PanoplanBuildPlanItem::getId)
                    .collect(Collectors.toList());
            QueryWrapper<PanoplanBuildPlanItemDetail> detailWrapper = new QueryWrapper<PanoplanBuildPlanItemDetail>();
            detailWrapper.in("pk_id", itemIds);
                    //.eq("is_send_back", isDel);
            List<PanoplanBuildPlanItemDetail> panoplanBuildPlanItemDetails = panoplanBuildPlanItemDetailMapper.selectList(detailWrapper);
            if (CollectionUtils.isNotEmpty(panoplanBuildPlanItemDetails)){
                panoPlanCastDecisionBO.setDetails(panoplanBuildPlanItemDetails);
            }

            return panoPlanCastDecisionBO;
        }

        return null;
    }

    @Override
    public PanoPlanCastDecisionBO selectCastDecisionById(String panoVersionId) {

        PanoPlanCastDecisionBO panoPlanCastDecisionBO = new PanoPlanCastDecisionBO();

        PanoplanBuildPlan panoplanBuildPlan = panoplanBuildPlanMapper.selectByPrimaryKey(panoVersionId,IsDeleteEnum.NO.getKey()+"");
        if(panoplanBuildPlan != null){

            queryCastDecisionInfo(IsDeleteEnum.NO.getKey(), panoPlanCastDecisionBO, panoplanBuildPlan);

            return panoPlanCastDecisionBO;
        }else{
            throw new MsgException(CodeEnum.NON_PANOPLAN_VERSION);
        }
    }

    @Override
    @Transactional
    public Map<String,Object> syncPanoplanBuildPlan(JSONObject panoplanBuildPlan) {
        try {
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
            Map<String, Object> map = new HashMap<>();
            List<PanoplanBuildPlanItem> planItemList = new ArrayList<>();
            List<PanoplanBuildPlanItemDetail> planItemDetailList = new ArrayList<>();
            JSONArray nodeDetail = null;
            if (null == panoplanBuildPlan || panoplanBuildPlan.isEmpty()) {
                throw new MsgException(CodeEnum.REQUEST_PARAM_NOT_FULL_ERROR);
            } else {
                String id = UUIDUtils.create();
                map.put("id", id);
                PanoplanBuildPlan newPanoplanBuildPlan = new PanoplanBuildPlan();
                String versionType = String.valueOf(panoplanBuildPlan.get("versionType"));
                String projectfID = String.valueOf(panoplanBuildPlan.get("projectfID"));
                map.put("versionType", versionType);
                map.put("projectfID", projectfID);
                newPanoplanBuildPlan.setId(id);
                newPanoplanBuildPlan.setOpnum(panoplanBuildPlan.getString("opnum"));
                newPanoplanBuildPlan.setPbnum(panoplanBuildPlan.getString("pbnum"));
                newPanoplanBuildPlan.setPlanVersion(panoplanBuildPlan.getString("planVersion"));
                newPanoplanBuildPlan.setProjectId(panoplanBuildPlan.getString("projectID"));
                newPanoplanBuildPlan.setProjectName(panoplanBuildPlan.getString("projectName"));
                newPanoplanBuildPlan.setProjectfId(projectfID);
                newPanoplanBuildPlan.setProjectfName(panoplanBuildPlan.getString("projectfName"));
                newPanoplanBuildPlan.setVersionStage(panoplanBuildPlan.getString("versionStage"));
                newPanoplanBuildPlan.setVersionCode(panoplanBuildPlan.getString("versionCode"));//看表注释
                newPanoplanBuildPlan.setVersionType(versionType);
                newPanoplanBuildPlan.setIsDeleted(String.valueOf(IsDeleteEnum.NO.getKey()));
                newPanoplanBuildPlan.setCreatedDate(LocalDateTime.now());
                //panoplanBuildPlanMapper.syncPanoplanBuildPlan(newPanoplanBuildPlan);

                JSONArray groupDetail = panoplanBuildPlan.getJSONArray("groupDetail");
                if (groupDetail.size() > 0) {
                    for (int i = 0; i < groupDetail.size(); i++) {
                        JSONObject jsonObject = groupDetail.getJSONObject(i);
                        String itemId = UUIDUtils.create();
//                        panoplanBuildPlanItemService.syncPanoplanBuildPlanItem(jsonObject,id,itemId);
                        if (null == jsonObject || jsonObject.isEmpty()) {
                            throw new MsgException(CodeEnum.REQUEST_PARAM_NOT_FULL_ERROR);
                        } else {
                            PanoplanBuildPlanItem newPanoplanBuildPlanItem = new PanoplanBuildPlanItem();

                            newPanoplanBuildPlanItem.setId(itemId);
                            newPanoplanBuildPlanItem.setPkId(id);
                            newPanoplanBuildPlanItem.setBatchId(jsonObject.getString("batchID"));
                            newPanoplanBuildPlanItem.setBatchCode(jsonObject.getString("batchCode"));
                            newPanoplanBuildPlanItem.setBatchName(jsonObject.getString("batchName"));
                            newPanoplanBuildPlanItem.setBatchNum(jsonObject.getString("batchNum"));
                            Object batchRoomNum = jsonObject.get("batchRoomNum");
                            if (null != batchRoomNum) {
                                newPanoplanBuildPlanItem.setBatchRoomNum(Integer.parseInt(batchRoomNum.toString()));
                            }
                            Object batchSaleArea = jsonObject.get("batchSaleArea");
                            if (null != batchSaleArea) {
                                newPanoplanBuildPlanItem.setBatchSaleArea(new BigDecimal(batchSaleArea.toString()));
                            }

                            newPanoplanBuildPlanItem.setBldPrdId(jsonObject.getString("bldPrdId"));
                            newPanoplanBuildPlanItem.setDecorateNum(jsonObject.getString("decorateNum"));
                            newPanoplanBuildPlanItem.setDecorateName(jsonObject.getString("decorateName"));
                            newPanoplanBuildPlanItem.setProType(jsonObject.getString("proType"));
                            newPanoplanBuildPlanItem.setProTypeCode(jsonObject.getString("proTypeCode"));
                            newPanoplanBuildPlanItem.setFormatBuildingCode(jsonObject.getString("formatBuildingCode"));
                            newPanoplanBuildPlanItem.setFormatBuildingName(jsonObject.getString("formatBuildingName"));
                            newPanoplanBuildPlanItem.setSaleNum(jsonObject.getString("saleNum"));
                            newPanoplanBuildPlanItem.setProductTypeName(jsonObject.getString("productTypeName"));
                            newPanoplanBuildPlanItem.setProductTypeNum(jsonObject.getString("productTypeNum"));
                            Object salePark = jsonObject.get("salePark");
                            if (null != salePark) {
                                newPanoplanBuildPlanItem.setSalePark(Integer.parseInt(salePark.toString()));
                            }
                            if (null != jsonObject.get("totalRoomNum")) {
                                newPanoplanBuildPlanItem.setTotalRoomNum(Integer.parseInt(jsonObject.get("totalRoomNum").toString()));
                            }
                            newPanoplanBuildPlanItem.setSaleType(jsonObject.getString("saleType"));
                            Object totalBuildArea = jsonObject.get("totalBuildArea");
                            if (null != totalBuildArea) {
                                newPanoplanBuildPlanItem.setTotalBuildArea(new BigDecimal(totalBuildArea.toString()));
                            }
                            if (null != jsonObject.get("batchBuildArea")) {
                                newPanoplanBuildPlanItem.setBatchBuildArea(new BigDecimal(jsonObject.get("batchBuildArea").toString()));
                            }
                            Object totalSaleArea = jsonObject.get("totalSaleArea");
                            if (null != totalSaleArea) {
                                newPanoplanBuildPlanItem.setTotalSaleArea(new BigDecimal(totalSaleArea.toString()));
                            }
                            String isDeleted = jsonObject.getString("isDeleted");
                            if (StringUtils.isNotEmpty(isDeleted)) {
                                newPanoplanBuildPlanItem.setIsDeleted(Integer.parseInt(isDeleted));
                            } else {
                                newPanoplanBuildPlanItem.setIsDeleted(IsDeleteEnum.NO.getKey());
                            }
                            //panoplanBuildPlanItemMapper.syncPanoplanBuildPlanItem(newPanoplanBuildPlanItem);
                            //planItemList.add(newPanoplanBuildPlanItem);

                            //JSONArray nodeDetail = jsonObject.getJSONArray("nodeDetail");
                            //优化楼栋子表-组团楼栋
                            //PanoplanBuildPlanItem planItem = getPanoplanBuildPlanItem(jsonObject, id, itemId);
                            planItemList.add(newPanoplanBuildPlanItem);
                            map.put("planItemList", newPanoplanBuildPlanItem);
                            nodeDetail = jsonObject.getJSONArray("nodeDetail");
                            if (nodeDetail.size() > 0) {
                                for (int j = 0; j < nodeDetail.size(); j++) {
                                    JSONObject nodeDetailItem = nodeDetail.getJSONObject(j);
                                    String itemDetailId = UUIDUtils.create();

                                        if (null == nodeDetailItem || nodeDetailItem.isEmpty() || null == itemId){
                                            throw new MsgException(CodeEnum.REQUEST_PARAM_NOT_FULL_ERROR);
                                        }else {
                                            PanoplanBuildPlanItemDetail newPanoplanBuildPlanItemDetail = new PanoplanBuildPlanItemDetail();
                                            newPanoplanBuildPlanItemDetail.setId(itemDetailId);
                                            newPanoplanBuildPlanItemDetail.setPkId(itemId);
                                            newPanoplanBuildPlanItemDetail.setVersionId(nodeDetailItem.getString("versinID"));
                                            newPanoplanBuildPlanItemDetail.setUniqueCode(nodeDetailItem.getString("uniqueCode"));
                                            newPanoplanBuildPlanItemDetail.setNodeCode(nodeDetailItem.getString("nodeCode"));
                                            newPanoplanBuildPlanItemDetail.setNodeName(nodeDetailItem.getString("nodeName"));
                                            String actualFinishDate = nodeDetailItem.getString("actualFinishDate");
                                            String plannedFinishDate = nodeDetailItem.getString("plannedFinishDate");
                                            String virtualFinishDate = nodeDetailItem.getString("virtualFinishDate");
                                            if (StringUtils.isNotEmpty(actualFinishDate)) {
                                                LocalDateTime newActualFinishDate = new Date(Long.parseLong(actualFinishDate)).toInstant().atOffset(ZoneOffset.of("+8")).toLocalDateTime();
                                                newPanoplanBuildPlanItemDetail.setActualFinishDate(newActualFinishDate);
                                            }
                                            if (StringUtils.isNotEmpty(plannedFinishDate)) {
                                                LocalDateTime newPlannedFinishDate = new Date(Long.parseLong(plannedFinishDate)).toInstant().atOffset(ZoneOffset.of("+8")).toLocalDateTime();
                                                newPanoplanBuildPlanItemDetail.setPlannedFinishDate(newPlannedFinishDate);
                                            }
                                            if (StringUtils.isNotEmpty(virtualFinishDate)) {
                                                LocalDateTime newVirtualFinishDate = new Date(Long.parseLong(virtualFinishDate)).toInstant().atOffset(ZoneOffset.of("+8")).toLocalDateTime();
                                                newPanoplanBuildPlanItemDetail.setVirtualFinishDate(newVirtualFinishDate);
                                            }

                                            String createdDate = nodeDetailItem.getString("createdDate");
                                            if (StringUtils.isNotEmpty(createdDate)) {
                                                LocalDateTime newCreatedDate = new Date(Long.parseLong(createdDate)).toInstant().atOffset(ZoneOffset.of("+8")).toLocalDateTime();
                                                newPanoplanBuildPlanItemDetail.setCreatedDate(newCreatedDate);
                                            }
                                            String updatedDate = nodeDetailItem.getString("updatedDate");
                                            if (StringUtils.isNotEmpty(updatedDate)) {
                                                LocalDateTime NewUpdatedDate = new Date(Long.parseLong(updatedDate)).toInstant().atOffset(ZoneOffset.of("+8")).toLocalDateTime();
                                                newPanoplanBuildPlanItemDetail.setUpdatedDate(NewUpdatedDate);
                                            }
                                            Integer isSendBack = nodeDetailItem.getInteger("isSendBack");
                                            if (null != isSendBack) {
                                                newPanoplanBuildPlanItemDetail.setIsSendBack(isSendBack);
                                            }
                                            //        panoplanBuildPlanItemDetailMapper.syncPanoplanBuildPlanItemDetail(newPanoplanBuildPlanItemDetail);
                                            //panoplanBuildPlanItemDetailMapper.insert(newPanoplanBuildPlanItemDetail);

                                            //PanoplanBuildPlanItemDetail planItemDetail = getPanoplanBuildPlanItemDetail(nodeDetailItem, itemId, itemDetailId);
                                            planItemDetailList.add(newPanoplanBuildPlanItemDetail);
                                            map.put("planItemDetailList", planItemDetailList);
                                        }
                                }
                            }
                        }
                    }
                }

                panoplanBuildPlanMapper.syncPanoplanBuildPlan(newPanoplanBuildPlan);
                panoplanBuildPlanItemMapper.insertBatch(planItemList);
                panoplanBuildPlanItemDetailMapper.insertBatch(planItemDetailList);

                return map;
            }
        }catch (Exception e){
            throw new MsgException(CodeEnum.REQUEST_PARAM_NOT_FULL_ERROR);
        }
    }

    @Override
    @Transactional
    public void syncAllData(JSONObject buildingPlanInfoLine, String id) {
        try {
            if (null == buildingPlanInfoLine || buildingPlanInfoLine.isEmpty() || null == id){
                throw new MsgException(CodeEnum.REQUEST_PARAM_NOT_FULL_ERROR);
            }else{
                PanoplanBuildPlan panoplanBuildPlan = new PanoplanBuildPlan();
                panoplanBuildPlan.setId(id);
                panoplanBuildPlan.setProjectId((String)buildingPlanInfoLine.get("projectID"));
                panoplanBuildPlan.setProjectName((String)buildingPlanInfoLine.get("projectName"));
                panoplanBuildPlan.setPbnum((String) buildingPlanInfoLine.get("pbnum"));
                panoplanBuildPlan.setProjectfId((String) buildingPlanInfoLine.get("projectfID"));
                panoplanBuildPlan.setProjectfName((String) buildingPlanInfoLine.get("projectfName"));
                panoplanBuildPlan.setOpnum((String) buildingPlanInfoLine.get("opnum"));
                panoplanBuildPlan.setVersionStage((String) buildingPlanInfoLine.get("versionStage"));
                panoplanBuildPlan.setVersionType((String) buildingPlanInfoLine.get("versionType"));
                panoplanBuildPlan.setPlanVersion((String) buildingPlanInfoLine.get("planVersion"));
                panoplanBuildPlan.setVersionCode((String) buildingPlanInfoLine.get("versionCode"));
                panoplanBuildPlan.setIsDeleted((String) buildingPlanInfoLine.get("isDeleted"));
                panoplanBuildPlan.setCreatedDate(LocalDateTime.now());
                panoplanBuildPlanMapper.syncPanoplanBuildPlan(panoplanBuildPlan);
            }
        } catch (Exception e) {
            throw new MsgException(CodeEnum.REQUEST_PARAM_NOT_FULL_ERROR);
        }

    }


    //优化楼栋计划-组团楼栋信息
    public PanoplanBuildPlanItem getPanoplanBuildPlanItem(JSONObject panoplanBuildPlanItem,String pkId,String itemId) {
        try {
            if (null == panoplanBuildPlanItem || panoplanBuildPlanItem.isEmpty() || null == pkId || null == itemId){
                throw new MsgException(CodeEnum.REQUEST_PARAM_NOT_FULL_ERROR);
            }else{
                PanoplanBuildPlanItem newPanoplanBuildPlanItem = new PanoplanBuildPlanItem();
                newPanoplanBuildPlanItem.setId(itemId);
                newPanoplanBuildPlanItem.setPkId(pkId);
                newPanoplanBuildPlanItem.setBatchId((String)panoplanBuildPlanItem.get("batchID"));
                newPanoplanBuildPlanItem.setBatchCode((String)panoplanBuildPlanItem.get("batchCode"));
                newPanoplanBuildPlanItem.setBatchName((String)panoplanBuildPlanItem.get("batchName"));
                newPanoplanBuildPlanItem.setBatchNum((String)panoplanBuildPlanItem.get("batchNum"));
                Object batchRoomNum = panoplanBuildPlanItem.get("batchRoomNum");
                if (null != batchRoomNum){
                    newPanoplanBuildPlanItem.setBatchRoomNum(Integer.parseInt(batchRoomNum.toString()) );
                }
                Object batchSaleArea = panoplanBuildPlanItem.get("batchSaleArea");
                if (null != batchSaleArea){
                    newPanoplanBuildPlanItem.setBatchSaleArea(new BigDecimal(batchSaleArea.toString()));
                }
                newPanoplanBuildPlanItem.setBldPrdId((String)panoplanBuildPlanItem.get("bldPrdId"));
                newPanoplanBuildPlanItem.setDecorateName((String)panoplanBuildPlanItem.get("decorateName"));
                newPanoplanBuildPlanItem.setFormatBuildingCode((String) panoplanBuildPlanItem.get("formatBuildingCode"));
                newPanoplanBuildPlanItem.setFormatBuildingName((String) panoplanBuildPlanItem.get("formatBuildingName"));
                newPanoplanBuildPlanItem.setProductTypeName((String) panoplanBuildPlanItem.get("productTypeName"));
                newPanoplanBuildPlanItem.setProductTypeNum((String) panoplanBuildPlanItem.get("productTypeNum"));
                Object salePark = panoplanBuildPlanItem.get("salePark");
                if (null != salePark){
                    newPanoplanBuildPlanItem.setSalePark(Integer.parseInt(salePark.toString()));
                }
                if (null != panoplanBuildPlanItem.get("totalRoomNum")){
                    newPanoplanBuildPlanItem.setTotalRoomNum(Integer.parseInt(panoplanBuildPlanItem.get("totalRoomNum").toString()));
                }
                newPanoplanBuildPlanItem.setSaleType((String) panoplanBuildPlanItem.get("saleType"));
                Object totalBuildArea = panoplanBuildPlanItem.get("totalBuildArea");
                if (null != totalBuildArea){
                    newPanoplanBuildPlanItem.setTotalBuildArea(new BigDecimal(totalBuildArea.toString()));
                }
                if (null != panoplanBuildPlanItem.get("batchBuildArea")){
                    newPanoplanBuildPlanItem.setBatchBuildArea(new BigDecimal(panoplanBuildPlanItem.get("batchBuildArea").toString()));
                }
                Object totalSaleArea = panoplanBuildPlanItem.get("totalSaleArea");
                if (null != totalSaleArea){
                    newPanoplanBuildPlanItem.setTotalSaleArea(new BigDecimal(totalSaleArea.toString()));
                }
                newPanoplanBuildPlanItem.setIsDeleted(IsDeleteEnum.NO.getKey());
                return newPanoplanBuildPlanItem;
            }
        } catch (Exception e) {
            throw new MsgException(CodeEnum.REQUEST_PARAM_NOT_FULL_ERROR);
        }
    }

    /**
     * 优化节点信息
     * @param panoplanBuildPlanItemDetail
     * @param pkId
     * @return
     */
    public PanoplanBuildPlanItemDetail getPanoplanBuildPlanItemDetail(JSONObject panoplanBuildPlanItemDetail, String pkId,String itemDetailId) {
        try {
            if (null == panoplanBuildPlanItemDetail || panoplanBuildPlanItemDetail.isEmpty() || null == pkId){
                throw new MsgException(CodeEnum.REQUEST_PARAM_NOT_FULL_ERROR);
            }else{
                String id = itemDetailId;
                PanoplanBuildPlanItemDetail newPanoplanBuildPlanItemDetail = new PanoplanBuildPlanItemDetail();
                newPanoplanBuildPlanItemDetail.setId(id);
                newPanoplanBuildPlanItemDetail.setPkId(pkId);
                newPanoplanBuildPlanItemDetail.setVersionId(panoplanBuildPlanItemDetail.getString("versinID"));
                newPanoplanBuildPlanItemDetail.setUniqueCode((String) panoplanBuildPlanItemDetail.get("uniqueCode"));
                newPanoplanBuildPlanItemDetail.setNodeCode((String) panoplanBuildPlanItemDetail.get("nodeCode"));
                newPanoplanBuildPlanItemDetail.setNodeName((String) panoplanBuildPlanItemDetail.get("nodeName"));
                Object actualFinishDate = panoplanBuildPlanItemDetail.get("actualFinishDate");
                Object plannedFinishDate = panoplanBuildPlanItemDetail.get("plannedFinishDate");
                Object virtualFinishDate = panoplanBuildPlanItemDetail.get("virtualFinishDate");
                if (null != actualFinishDate){
                    LocalDateTime newActualFinishDate = new Date(Long.parseLong(actualFinishDate.toString())).toInstant().atOffset(ZoneOffset.of("+8")).toLocalDateTime();
                    newPanoplanBuildPlanItemDetail.setActualFinishDate(newActualFinishDate);
                }
                if (null != plannedFinishDate){
                    LocalDateTime newPlannedFinishDate = new Date(Long.parseLong(plannedFinishDate.toString())).toInstant().atOffset(ZoneOffset.of("+8")).toLocalDateTime();
                    newPanoplanBuildPlanItemDetail.setPlannedFinishDate(newPlannedFinishDate);
                }
                if (null != virtualFinishDate){
                    LocalDateTime newVirtualFinishDate = new Date(Long.parseLong(virtualFinishDate.toString())).toInstant().atOffset(ZoneOffset.of("+8")).toLocalDateTime();
                    newPanoplanBuildPlanItemDetail.setVirtualFinishDate(newVirtualFinishDate);
                }
                newPanoplanBuildPlanItemDetail.setCreatedDate(LocalDateTime.now());
                newPanoplanBuildPlanItemDetail.setIsSendBack(0);
                return newPanoplanBuildPlanItemDetail;
            }
        } catch (MsgException e) {
            throw new MsgException(CodeEnum.REQUEST_PARAM_NOT_FULL_ERROR);
        }
    }

    @Override
    public PanoPlanCastDecisionBO selectById(String sourcePlan) {
        PanoPlanCastDecisionBO panoPlanCastDecisionBO = new PanoPlanCastDecisionBO();
        PanoplanBuildPlan panoplanBuildPlan = panoplanBuildPlanMapper.selectByPrimaryKey(sourcePlan, String.valueOf(IsDeleteEnum.NO.getKey()));
        if(panoplanBuildPlan != null){
            //分期
            panoPlanCastDecisionBO.setPanoplanBuildPlan(panoplanBuildPlan);
            //组团
            QueryWrapper<PanoplanBuildPlanItem> groupWrapper = new QueryWrapper<PanoplanBuildPlanItem>();
            groupWrapper.eq("pk_id", panoplanBuildPlan.getId()).last(" GROUP BY batch_id");
            List<PanoplanBuildPlanItem> groupItems = panoplanBuildPlanItemMapper.selectList(groupWrapper);
            if(CollectionUtils.isNotEmpty(groupItems)){
                panoPlanCastDecisionBO.setGroupItems(groupItems);
            }else{
                //楼栋子表-组团楼栋表数据为空,请在楼栋计划系统 推送一条数据
                CodeEnum.NON_PANOPLAN_GROUP.setMessage("楼栋计划 "+CodeEnum.NON_PANOPLAN_GROUP.getMessage());
                throw new MsgException(CodeEnum.NON_PANOPLAN_GROUP);
            }
            //产品构成
            QueryWrapper<PanoplanBuildPlanItem> productWrapper = new QueryWrapper<PanoplanBuildPlanItem>();
            productWrapper.eq("pk_id", panoplanBuildPlan.getId()).last(" GROUP BY batch_id, product_type_num");
            List<PanoplanBuildPlanItem> productItems = panoplanBuildPlanItemMapper.selectList(productWrapper);
            if(CollectionUtils.isNotEmpty(productItems)){
                panoPlanCastDecisionBO.setProductItems(productItems);
            }else{
                //楼栋子表-组团楼栋表数据为空,请在楼栋计划系统 推送一条数据
                CodeEnum.NON_PANOPLAN_PRODUT.setMessage("楼栋计划 "+CodeEnum.NON_PANOPLAN_PRODUT.getMessage());
                throw new MsgException(CodeEnum.NON_PANOPLAN_PRODUT);
            }
            //楼栋
            QueryWrapper<PanoplanBuildPlanItem> buildWrapper = new QueryWrapper<PanoplanBuildPlanItem>();
            buildWrapper.eq("pk_id", panoplanBuildPlan.getId()).last(" GROUP BY batch_id, product_type_num, bld_prd_Id");
            List<PanoplanBuildPlanItem> buildItems = panoplanBuildPlanItemMapper.selectList(buildWrapper);
            if(CollectionUtils.isNotEmpty(buildItems)){
                panoPlanCastDecisionBO.setBuildItems(buildItems);
            }else{
                //楼栋子表-组团楼栋表数据为空,请在楼栋计划系统 推送一条数据
                CodeEnum.NON_PANOPLAN_BUILD.setMessage("楼栋计划 "+CodeEnum.NON_PANOPLAN_BUILD.getMessage());
                throw new MsgException(CodeEnum.NON_PANOPLAN_BUILD);
            }
            //供货时间节点
            List<String> itemIds = Optional.of(buildItems).orElseGet(ArrayList::new)
                    .stream().map(PanoplanBuildPlanItem::getId)
                    .collect(Collectors.toList());
            QueryWrapper<PanoplanBuildPlanItemDetail> detailWrapper = new QueryWrapper<PanoplanBuildPlanItemDetail>();
            detailWrapper.in("pk_id", itemIds);
            List<PanoplanBuildPlanItemDetail> panoplanBuildPlanItemDetails = panoplanBuildPlanItemDetailMapper.selectList(detailWrapper);
            if (CollectionUtils.isNotEmpty(panoplanBuildPlanItemDetails)){
                panoPlanCastDecisionBO.setDetails(panoplanBuildPlanItemDetails);
            }
            return panoPlanCastDecisionBO;
        }else{
            throw new MsgException(CodeEnum.NON_APPOINT_PANOPLAN_VERSION);
        }
    }

}
